<?
// COMP3311 HTTP Library
// Written by John Shepherd, 2003-2007

# getParams
# - get params to a script, with checking and defaults
# - looks at $_GET, $_POST, $_COOKIES arrays for values
# - returns array(name1=>val1, name2=>val2,...)

function getParams($inputs)
{
	$values = array(); $errs = array();
	foreach ($inputs as $name => $desc)
	{
		list($type,$stat) = $desc;
		$type = strtolower($type);
		$stat = strtolower($stat);
		if ($stat != "optional" && $stat != "required")
			$errs[] = "Bad declaration for param '$name'";
		if ($stat == "optional")
			$def = (count($desc) == 3) ? $desc[2] : null;
		if ($name == "") continue;
		if (!array_key_exists($name,$_REQUEST))
			$val = "";
		else
			$val = $_REQUEST["$name"];
		if ($val == "") {
			if ($stat == "optional")
				$val = $def;
			else
				$errs[] = "Required param '$name' missing";
		}
		// TODO: add type checking in here eventually
		$a = strpos($type,"[");
		if ($a === false) {
			if (!is_null($val))
				$val = stripslashes(urldecode($val));
			if ($type != "string") $val = trim($val);
		}
		else {
			$b = strpos($type,"]");
			$type = substr($type,$a+1,$b-$a+1);
			for ($i = 0; $i < count($val); $i++) {
				if (!is_null($val[$i]))
					$val[$i] = stripslashes(urldecode($val[$i]));
				if ($type != "string") $val[$i] = trim($val[$i]);
			}
		}
		$values[$name] = $val;
	}
	if (count($errs) == 0)
		return $values;
	else {
		echo "<html><head><title>Internal Error</title></head>\n";
		echo "<body><center><h2 style='color:red'>Internal Error</h2>\n";
		foreach ($errs as $err) echo $err."<p>\n";
		echo "</body></html>\n";
		exit;
	}
}

# paramList(params)
# - create a URL-encoded string of name=value pairs

function paramList($params)
{
	$list = array();
	foreach ($params as $name => $value) {
		$p = oneParam($name,$value);
		if ($p != "") $list[] = $p;
	}
	return join("&",$list);
}

# oneParam(name,value)
# - generate a single param=value element

function oneParam($name,$value)
{
	if (!def($name) || !def($value))
		return "";
	else
		return "$name=".htmlVal(urlencode($value));
}


# mkURL(url,args)
# - build a URL from a script name and param array

function mkURL()
{
	$argv = func_get_args();
	$url = $argv[0];
	for ($i = 1; $i < count($argv); $i++)
	{
		$p = $argv[$i];
		if (is_array($p))
			$p = paramList($p);
		if ($p == "")
			continue;
		elseif (strchr($url,"?"))
			$url .= "&$p";
		else
			$url .= "?$p";
	}
	return $url;
}

# giveUp(fromURL)
# - displays an error message on the browser; dead-end page
# - assumes we have an errors/ directory containing handler scripts

function giveUp($url)
{
	goto(mkURL("errors/fatal.php",oneParam("msg",$url)));
}

# scriptName()
# - returns script name relative to top-level of system

function scriptName()
{
	$name = str_replace(ROOT."/","",$_SERVER["SCRIPT_FILENAME"]);
	$name = str_replace(PATH."/","",$name);
	return $name;
}

# setURL()
# - set $_SESSION['myLastURL'] and return previous value

function setURL()
{
	if (isset($_SESSION['myCurrURL']))
		$_SESSION['myPrevURL'] = $_SESSION['myCurrURL'];
	else
		$_SESSION['myPrevURL'] = URL."/index.php";
	$_SESSION['myCurrURL'] = mkURL($_SERVER['PHP_SELF'],$_GET);
	return $_SESSION['myCurrURL'];
}

# thisURL()
# - attempts to reconstruct the calling URL for the current page

function thisURL()
{
	return mkURL(scriptName(),$_GET);
}

# goto(url)
# - jump to specified page
# - page is treated relative to top-level of system NOT to current page
# - assumes no HTML output has occurred yet
# - if it has, we try transfer via <meta> tag ... might work

function goto($page)
{
	$url = URL."/$page";
	if (!headers_sent())
		header("Location: $url");
	else
		echo "<meta http-equiv='refresh'".
		     " content='0;URL=$url'>\n".
		     "</table>\n</body>\n</html>\n";
	exit;
}

?>
